﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using MyBlog2.Repository;
using MyBlog2.Models;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;

namespace Microsoft.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class HomeController : Controller
    {
        //private readonly AppDbContext _context;

        private readonly IUserRepository _userRepository;

        public HomeController(IUserRepository userRepository)
        {
            this._userRepository = userRepository;
        }

       
        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var loginUser = _userRepository.Login(user);

            if (loginUser == null)
            {
                return BadRequest("用户名或密码错误！");
            }

            var claims = new List<Claim> {
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim(ClaimTypes.Role,"admin"),
            };

            ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login");
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.SignInAsync(claimsPrincipal);
            return Redirect("/Admin/AdminManage/Index");
            
        }


        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }



    }
}